<template>
    <public-dialog
            :title="titleName + '部门专属任务'"
            :width="'40%'"
            :confirmButtonTitle="'提交'"
            v-model:visible="visible"
            @onConfirm="onConfirm"
    >
        <el-form
                :model="questForm"
                ref="questFormRef"
                :rules="rules"
                label-width="160px"
        >
            <el-row>
                <el-col :span="20">
                    <el-form-item label="所属项目阶段">
                        <el-input
                                disabled
                                v-model="questForm.stageName"
                                placeholder=""
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item label="实施任务名称" prop="taskName">
                        <el-input
                                v-model="questForm.taskName"
                                placeholder="请输入实施任务名称"
                                :maxlength="20"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item label="实施计划范围" prop="time">
                        <el-date-picker
                                v-model="questForm.time"
                                @change="handelChangeTime"
                                type="datetimerange"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                size="large"
                                :disabledDate="disabledDateFn"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item
                            label="主责任部门"
                            prop="responsibleDepartmentId"
                    >
                            <el-select
                                    filterable
                                    v-model="questForm.responsibleDepartmentId"
                                    clearable
                                    placeholder="选择部门"
                                    @change="
										departmentIdChange(questForm.responsibleDepartmentId)
									"
                            >
                                <el-option
                                        v-for="item in state.allDepartmentList"
                                        :key="item.departmentId"
                                        :label="item.departmentName"
                                        :value="item.departmentId"
                                />
                            </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item label="任务类型">
                        <el-select
                                v-model="questForm.taskType"
                                clearable
                                :disabled="state.isZb"
                                placeholder="请选择任务类型"
                        >
                            <el-option :value="1" label="部门专属任务"></el-option>
                            <el-option :value="2" label="公共任务"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item label="任务关联" >
                        <el-select
                                v-model="questForm.taskChooseType"
                                clearable
                                disabled
                                placeholder="请选择任务关联"
                        >
                            <el-option label="向上串行(关联任务为前置任务)" :value="1"></el-option>
                            <el-option label="向下串行(关联任务为后置任务)" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item label="关联阶段已建任务" prop="commonTaskId">
                        <el-select
                            v-model="questForm.commonTaskId"
                            clearable
                            placeholder="请选择关联任务"
                        >
                            <el-option
                                v-for="item in state.allTaskList"
                                :label="item.taskName"
                                :key="item.projectTaskId"
                                :value="item.projectTaskId"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </public-dialog>
</template>

<script setup>
import {ElCol, ElForm, ElFormItem, ElInput, ElMessage, ElRow} from "element-plus";
import PublicDialog from "@/components/PublicDialog.vue";
import {reactive, ref, watch} from "vue";
import {department, projectTask, projectTaskApi} from "@/api/project";
import {resetForm} from "@/common/utils/GlobalUtils";

const state = reactive({
    predictStartTime:'',
    predictEndTime:'',
    allTaskList: [],
    isZb: true,
    treeNode: null, //树节点
    departmentPersonList: [],
    allDepartmentList: [],
    tableList: [],
    projectStageId: "",
    data: {
        projectName: "",
        predictStartTime: "",
        predictEndTime: "",
        responsibleDepartmentName: "",
    },
    dateList: [],
    btnActiveName: "0",
    ganttList: [{}],
});

const visible = ref(false);
const questForm = reactive({taskChooseType:1,taskName:''});
const titleName = ref('创建');
const rules = reactive({
    taskName: [
        { required: true, message: "请输入实施任务名称", trigger: "blur" },
    ],
    time: [{ required: true, message: "请选择实施计划范围", trigger: "change" }],
    responsibleDepartmentId: [
        { required: true, message: "请选择任务主责部门/单位", trigger: "change" },
    ],
    taskType: [{ required: true, message: "请选择任务类型", trigger: "change" }],
    commonTaskId: [{ required: true, message: "请选择关联阶段已建任务", trigger: "change" }],
});

/**
 * 实施计划范围
 * @param e
 */
const handelChangeTime = (e) => {
    if (e && e.length > 0) {
        questForm.planStartTime = e[0];
        questForm.planEndTime = e[1];
    }
};

/**
 * 选择项目立项部门
 * @param id
 */
const departmentIdChange = (id) => {
   /* questForm.responsibleUserId = "";
    if (id === "-5515261004502579607") {
        state.isZb = false;
        questForm.taskType = 1;
        questForm.taskChooseType = 1;
    } else {
        state.isZb = true;
        questForm.taskType = 2;
        questForm.taskChooseType = '';
    }*/
};

const questFormRef = ref(null);
const emits = defineEmits(['onSuccess']);

/**
 * 确认
 */
const onConfirm = () => {
    questFormRef.value.validate((valid) => {
        if (valid) {
            if (titleName.value === "创建") {
                projectTask.addProjectTask(questForm).then((res) => {
                    if (res.code === '200') {
                        visible.value = false;
                        ElMessage.success("新增成功");
                        emits('onSuccess');
                    }
                });
            }

            if(titleName.value === "编辑") {
                projectTask.updateTask(questForm).then((res) => {
                    if (res.code === '200') {
                        ElMessage.success("编辑成功");
                        visible.value = false;
                        emits('onSuccess');
                    }
                });
            }
        }
    });
};

//获取当前阶段公共任务
const getAactiveDepartmentTask = (stageId) => {
    projectTaskApi.getStageAllTask(stageId).then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            state.allTaskList = data;
        }
    });
};

// 获取所有部门
const getAllDepartments = () => {
    department.getAllDepartments().then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            state.allDepartmentList = data.filter(item=>{
                if(item.departmentId === '-5515261004502579607'){
                    return item;
                }
            })
        }
    });
};

/**
 * 打开弹窗
 */
const openPopup = (title,state1,row) => {
    getAllDepartments();
    getAactiveDepartmentTask(state1.projectStageId);
    titleName.value = title;
    visible.value = true;

    state.predictStartTime = state1.stage.predictStartTime;
    state.predictEndTime = state1.stage.predictEndTime;
    if (titleName.value === "创建") {
        let params = {
            projectStageId: state1.projectStageId,
            projectName: state1.data.projectName,
            projectId: state1.data.projectId,
            taskType:1,
            taskChooseType:1,
            commonTaskId:'',
            taskName:'',
            responsibleDepartmentId:'',
            responsibleUserId:'',
            time:[],
            planStartTime:'',
            planEndTime:'',
            stageName:state1.stageName,
            predictStartTime:state1.predictStartTime,
            predictEndTime:state1.predictEndTime,
        };
        for(let key in state1){
            state[key] = state1[key];
        }
        for(let key in params){
            questForm[key] = params[key];
        }
        if (questFormRef.value) {
            setTimeout(()=>{
                questFormRef.value.clearValidate();
            });
        }
    }

    if(titleName.value === '编辑'){
        for(let key in row){
            questForm[key] = row[key];
        }
    }
}

/**
 * 限制时间可选范围
 */
const disabledDateFn = (time) => {
    return  !(time.getTime() >= new Date(state.predictStartTime).getTime()-86400000) || !(time.getTime() <= new Date(state.predictEndTime).getTime())
}

/**
 * 关闭弹窗
 */
const closePopup = () => {

}

defineExpose({openPopup,closePopup});
</script>
